package common

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

type Mongo struct {
	Client     *mongo.Client
	Collection *mongo.Collection
}

var (
	GMongo *Mongo
)

func InitMongo() (err error) {

	GMongo = &Mongo{}
	option := options.Client().ApplyURI(GConfig.Viper.GetString("MongodbUri"))
	if GMongo.Client, err = mongo.Connect(context.TODO(), option); err != nil {
		return
	}
	GMongo.Collection = GMongo.Client.Database(GConfig.Viper.GetString("MongodbName")).Collection(GConfig.Viper.GetString("MongodbTable"))

	return
}

func (mon *Mongo) Logs(name string, limit, skip int64) (res *LogRes, err error) {

	var (
		cursor *mongo.Cursor
	)
	res = &LogRes{
		LogArr: make([]*JobLog, 0),
		Count:  0,
	}
	filter := struct {
		JobName string `bson:"jobName"`
	}{JobName: name}
	logSort := struct {
		SortOrder int `bson:"startTime"` // {startTime:-1}
	}{SortOrder: -1}
	opts := options.FindOptions{
		Skip:  &skip,
		Sort:  logSort,
		Limit: &limit,
	}
	if res.Count, err = mon.Collection.CountDocuments(context.TODO(), filter); err != nil {
		return
	}
	if cursor, err = mon.Collection.Find(context.TODO(), filter, &opts); err != nil {
		return
	}
	defer cursor.Close(context.TODO())
	for cursor.Next(context.TODO()) {
		nlog := &JobLog{}
		if err = cursor.Decode(nlog); err != nil {
			log.Println(err)
			continue
		}
		res.LogArr = append(res.LogArr, nlog)
	}

	return
}
